<?php

namespace App\Models\System;

use App\Components\Redis;
use Illuminate\Database\Eloquent\Model;

class SystemRole extends Model
{
    protected $table = 'system_role';

    public static function node(int $roleId): array
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMROLE:NODE:' . $roleId;
        $cacheRs = Redis::get($cacheKey);
        if ($cacheRs !== false && $cacheRs !== null) {
            return json_decode($cacheRs, true);
        }

        $nodeRs = SystemRoleNode::select('id', 'node')
            ->where('role_id', $roleId)
            ->orderBy('id', 'asc')
            ->get()->toArray();
        $nodeRs = array_column($nodeRs, 'node');
        Redis::setex($cacheKey, Redis::mediumTime(), json_encode($nodeRs));
        return $nodeRs;
    }

    public static function clearNodeCache(int $roleId): bool
    {
        $cacheKey = 'MODELS:SYSTEM:SYSTEMROLE:NODE:' . $roleId;
        Redis::del($cacheKey);
        return true;
    }
}
